from langchain.indexes import SQLRecordManager, index
from langchain_core.documents import Document
from langchain_elasticsearch import ElasticsearchStore
from langchain_ollama import OllamaEmbeddings
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

collection_name = "test_index"

#使用Ollama的嵌入模型
embeddings_model = OllamaEmbeddings(
        base_url='http://192.168.1.109:11434',
        model="nomic-embed-text")

vectorstore = ElasticsearchStore(
    es_url="http://127.0.0.1:9200/",
    index_name="test_index",
    embedding=embeddings_model,
)

namespace = f"elasticsearch/{collection_name}"
record_manager = SQLRecordManager(
    namespace, db_url="sqlite:///record_manager_cache.sql"
)
record_manager.create_schema()
doc1 = Document(page_content="kitty", metadata={"source": "kitty.txt"})
doc2 = Document(page_content="doggy", metadata={"source": "doggy.txt"})

def _clear():
    """Hacky helper method to clear content. See the `full` mode section to understand why it works."""
    index([], record_manager, vectorstore, cleanup="full", source_id_key="source")

_clear()
print (index(
    [doc1, doc1, doc1, doc1, doc1],
    record_manager,
    vectorstore,
    cleanup=None,
    source_id_key="source",
))
_clear()
print(
    index([doc1, doc2], record_manager, vectorstore, cleanup=None, source_id_key="source")
)